<?php
namespace App\Http\Controllers\Manage\Game;

use App\Http\Controllers\Manage\CommonController;
use App\Model\Game\Game;
use App\Model\Member\Member;
use App\Model\Wechat\WechatMp;
use App\Model\Wechat\WechatMpGame;
use Illuminate\Support\Facades\DB;

class GameController extends CommonController
{
    /**
     * 查看游戏
     * @return mixed
     */
    public function index()
    {
        $field = [
            'id' => '游戏编号',
            'name' => '游戏名称',
            'type' => '游戏类型',
            'resource' => '资源地址',
            'create_time' => '发布时间'
        ];
        $viewData = [];
        $viewData['title'] = '游戏管理';
        $viewData['range'] = [
            'type' => gameType()
        ];
        # 查询字段
        $viewData['field'] = $field;
        # 列表操作菜单
        $viewData['option_title'] = [
            'plus' => [
                'title' => '发布新游戏',
                'route' => route('manage.game.resource.create')
            ]
        ];
        # 行表操作菜单
        $page = $this->request->input('page', 1);
        $viewData['option_row'] = [
            'edit' => [
                'title' => '编辑',
                'route' => 'manage.game.resource.edit',
                'param' =>   [
                    'page' => $page
                ]
            ]
        ];
        # 页面模态对话框
        $viewData['option_modal'] = [];
        # 查询记录
        $game = new Game();
        $viewData['list'] = $this->constraintSelect($game, $field);
        # 渲染视图
        return view('manage.table', $viewData);
    }

    /**
     * 创建游戏页面
     * @return mixed
     */
    public function create()
    {
        # 表单元素
        $param = [];
        $param['name'] = [
            'name' => '游戏名称',
            'type' => 'text',
            'col' => '4'
        ];
        $param['price'] = [
            'name' => '游戏价格',
            'type' => 'text',
            'col' => '4'
        ];
        $param['dir'] = [
            'name' => '游戏简称(小写首字母)',
            'type' => 'text',
            'col' => '4'
        ];
      /*  $param['dir'] = [
            'name' => '上传游戏简称',
            'type' => 'text',
            'col' => '6'
        ];*/


        $param['resource'] = [
            'name' => '上传游戏',
            'type' => 'file',
            'accept'=> "zip",
            'col' => '6'
        ];
        $param['type'] = [
            'name' => '游戏类型',
            'type' => 'select',
            'col' => '6',
            'range' => gameType()
        ];
        $param['description'] = [
            'name' => '游戏描述',
            'type' => 'text',
            'col' => '12'
        ];
       /* $param['thumb'] = [
            'name' => '游戏缩略预览图（建议256×256像素）',
            'type' => 'thumb',
            'col' => '3',
            'accept' => 'image',
            'ratio' => '1'
        ];*/

        foreach ($param as $key => $value) {
            $param[$key]['value'] = $this->request->old($key);
        }
        $viewData = [];
        $viewData['title'] = '发布新游戏';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.game.resource.store');
        $viewData['form_method'] = 'POST';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回游戏列表',
                'type' => 'button',
                'route' => route('manage.game.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset'
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);
    }

    /**
     *
     * 创建游戏页面
     *
     * @param ProductPostRequest $request
     * @return mixed
     */
    public function store()
    {
       
        $this->request->flash();
        if (!$this->request->has('name')) {
            return redirect()->back()->with('error', '请填写游戏名称');
        }
        if (!$this->request->has('description')) {
            return redirect()->back()->with('error', '请填写游戏描述');
        }
        if (!$this->request->has('dir')) {
            return redirect()->back()->with('error', '请填写游戏简称');
        }
        if (!$this->request->hasFile('resource')) {
            return redirect()->back()->with('error', '请上传游戏包');
        }
        # 文件名处理
       /* $file = $_FILES['resource'];
        $filename = $file['name'];
        $filenameStr = explode('.', $filename);*/
        //dd($file['tmp_name']);
        $file = $this->request->file('resource');
        $ext = $file -> getClientOriginalExtension();
        if(!isset($ext) || $ext!= 'zip') {
            return redirect()->back()->with("error", '不是zip格式的文件');
        }
       // $username = $filenameStr[0];
       // $ext = $filenameStr[1];
        $newName = $this->request->input('dir').".".$ext;
        #自动转换名称成英文首字母缩写
        //$dir = $this->getAllChar($this->request->input('name'));*/
        $assetsPath = env('ASSETS_PATH');
        $newPath = $assetsPath . 'tmp/';
        if (!file_exists($newPath)) {
            @mkdir($newPath,0777, true);
        }
        $path = 'wechat_game/'.$this->request->input('dir')."/";
        $games = Game::where('resource',$path)->first();
        if($games){
            return redirect()->back()->with("error", '游戏简称已存在，请更换一个');
        }
        $desDir = $assetsPath.$path;
        //dd($desDir);
//        $filePath = $assetsPath . $wechatMpGame->resource . $file['name'];
        //$filePath = $assetsPath . 'tmp/';

//        $newPath = $newPath . $newName;
       // $newPath = $newPath . $file['name'];
       /* if (!file_exists($newPath)) {
            @mkdir($newPath,0777, true);
        }
        //dd($newPath);exit;
        if(!move_uploaded_file($file['tmp_name'], $newPath)) {
            return redirect()->back()->with("error", 'Upload file wrong');
        }*/
       /* if ($file->isValid()) {
            if(!move_uploaded_file($newName, $newPath)) {
                return redirect()->back()->with('error', '上传失败');
            }
           $file -> move($newPath,$newName);
           $this->unzip($newPath.$newName,$desDir);
        }*/
        $file -> move($newPath,$newName);
       // $newPath = $assetsPath . $mpGame->resource .$member->username.'_'. $id .'.zip';
        $this->unzip($newPath.$newName,$desDir);
        # 插入新数据
        $game = new Game();
        $game->name = $this->request->input('name');
        $game->description = $this->request->input('description');
        $game->resource = 'wechat_game/'.$this->request->input('dir')."/";
        $game->price= $this->request->input('price');
        $game->image_path= "image";
        $game->audio_path= "audio";
        $game->thumb= "1.jpg";
        $game->type = $this->request->input('type');
        $game->create_user = $this->user['id'];
        if ($game->save()) {
            # 创建成功后跳转到游戏详细介绍编辑页
            return redirect()->route('manage.game.resource.index')->with('success', '游戏创建成功!');
        }
        return redirect()->back()->with('error', '游戏创建失败!');
    }

    /**
     * 修改管理员信息页面
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $game = Game::find($id);
        # 表单元素
        $param = [];
        $param['name'] = [
            'name' => '游戏名称',
            'type' => 'text',
            'col' => '6',
            'value' => $game->name
        ];
        $param['price'] = [
            'name' => '游戏价格',
            'type' => 'text',
            'col' => '6',
            'value' => $game->price
        ];
        $param['resource'] = [
            'name' => '资源地址',
            'type' => 'text',
            'col' => '6',
            'value' => $game->resource
        ];
        $param['description'] = [
            'name' => '游戏描述',
            'type' => 'text',
            'col' => '12',
            'value' => $game->description
        ];
        $param['type'] = [
            'name' => '游戏类型',
            'type' => 'select',
            'col' => '12',
            'range' => gameType(),
            'value' => $game->type
        ];
        $param['thumb'] = [
            'name' => '游戏缩略预览图',
            'type' => 'img',
            'col' => '3',
            'value' => env("ASSETS_PATH").$game->resource.$game->thumb,
            'ratio' => '1'
        ];

        foreach ($param as $key => $value) {
            if ($this->request->old($key)) $param[$key]['value'] = $this->request->old($key);
        }
        $viewData = [];
        $viewData['title'] = '修改游戏信息';
        $viewData['form'] = $this->form($param);
        $page = $this->request->input('page', 1);
        $viewData['form_url'] = route('manage.game.resource.update', ['id' => $id, 'page' => $page]);
        $viewData['form_method'] = 'PUT';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回游戏列表',
                'type' => 'button',
                'route' => route('manage.game.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset'
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        # 渲染视图
        return view('manage.form', $viewData);
    }

    /**
     *
     * 修改游戏规则操作
     *
     * @param GamePostRequest $request
     * @param $id
     * @return mixed
     */
    public function update($id)
    {
        $game = Game::find($id);
        $this->request->flash();
        if (!$this->request->has('name')) {
            return redirect()->back()->with('error', '请填写游戏名称');
        }
        if (!$this->request->has('resource')) {
            return redirect()->back()->with('error', '请填写资源地址');
        }
        $game->name = $this->request->input('name');
        $game->resource = $this->request->input('resource');
        $game->description = $this->request->input('description');
        $game->price = $this->request->input('price');
        $game->type = $this->request->input('type');
        $game->update_user = $this->user['id'];
        if(!$game->save()) {
            return redirect()->back()->with('error', '游戏修改失败');
        }
        $page = $this->request->input('page', 1);
        $param = [
            'page' => $page
        ];
        return redirect()->route('manage.game.resource.index', $param)->with('success', '游戏修改成功');
    }

}
